﻿using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RK.FormPlugin.GFT
{
    [Description("GFT:批量修改生产用料清单插件"), HotUpdate]
    public class Pae_plxgscyl : AbstractDynamicFormPlugIn
    {
        string spartno = "0", tpartno = "0", orgid = "0"; //原物料编号、新物料编号、生产组织
        string tjd = "0";//原物料及新物料计算精度
        public override void AfterEntryBarItemClick(AfterBarItemClickEventArgs e)
        {
            base.AfterEntryBarItemClick(e);
            switch (e.BarItemKey)
            {
                case "tbButtonFresh":


                    {
                        string billtype = ((DynamicObject)this.Model.GetValue("FBillTypeID"))["Name"].ToString();
                        spartno = this.Model.GetValue("F_PAEZ_SMaterialId") != null ? ((DynamicObject)this.Model.GetValue("F_PAEZ_SMaterialId"))[1].ToString() : "0";
                        tpartno = this.Model.GetValue("F_PAEZ_TMaterialId") != null ? ((DynamicObject)this.Model.GetValue("F_PAEZ_TMaterialId"))[1].ToString() : "0";
                        orgid = this.Model.GetValue("F_PAEZ_OrgId") != null ? ((DynamicObject)this.Model.GetValue("F_PAEZ_OrgId"))[0].ToString() : "0";

                        if (((spartno != "0" && tpartno != "0" && billtype == "按物料修改") || (spartno != "0" && billtype == "按用量修改")) && this.View.OpenParameter.Status.ToString().ToUpper() == "ADDNEW")
                        {
                            this.fillgrid();
                        }
                        break;
                    }
                //清除无用记录
                case "tbDelete":

                    {
                        this.Model.BeginIniti();
                        for (int i = 0; i < this.Model.GetEntryRowCount("FEntity"); i++)
                        {
                            if (this.Model.GetValue("FChecked", i).ToString() == "False")
                            {
                                this.Model.DeleteEntryRow("FEntity", i);
                                i -= 1;
                            }
                        }
                        this.Model.EndIniti();
                        this.View.UpdateView("FEntity");
                        break;
                    }
            }
        }
        public override void BeforeUpdateValue(BeforeUpdateValueEventArgs e)
        {
            StringBuilder errorsb = new StringBuilder();
            switch (e.Key.ToString())
            {
                case "FChecked": //选取，有开领料单但未审核时，不可以选取
                    {

                        //this.View.ShowErrMessage("点击了选取按钮！");
                        StringBuilder sb = new StringBuilder();
                        //取用料单内码
                        string FFPPBOMENTRYID = this.Model.GetValue("FFPPBOMENTRYID") != null ? this.Model.GetValue("FFPPBOMENTRYID").ToString() : "0";
                        errorsb.Clear();
                        using (IDataReader rd = DBServiceHelper.ExecuteReader(this.Context, string.Format("/*dialect*/ select  b.FBILLNO from T_PRD_PICKMTRLDATA a inner join  T_PRD_PICKMTRL b on a.fid=b.fid where a.FPPBOMENTRYID={0} and b.FDOCUMENTSTATUS<>'C'", FFPPBOMENTRYID)))
                        {
                            while (rd.Read())
                            {
                                errorsb.AppendLine(string.Format("本生产用料清单有顀料单【{0}】未审核，不可以修改用料单！", rd[0].ToString()));
                            }
                            if (errorsb.ToString() != "")
                            {
                                this.View.ShowErrMessage(errorsb.ToString());
                                e.Cancel = true;
                            }
                        }
                        break;
                    }
                case "FTMustQty":  //手动修改新物产需求数
                    {
                        if (tjd == "0" && e.Value != null) //计量单位要求取整
                        {
                            if (Convert.ToDouble(e.Value) > 0)
                            { e.Value = Math.Ceiling(Convert.ToDouble(e.Value)); }
                        }
                        break;
                    }
                case "FOldQty":  //手动修改新物产需求数
                    {
                        if (Convert.ToDouble(e.Value) < 0)
                        {
                            this.View.ShowErrMessage("原物料的分配不可以少于0！");
                            e.Cancel = true;
                        }
                        if (tjd == "0" && e.Value != null) //计量单位要求取整
                        {
                            if (Convert.ToDouble(e.Value) > 0)
                            { e.Value = Math.Ceiling(Convert.ToDouble(e.Value)); }
                        }
                        break;
                    }
            }
            base.BeforeUpdateValue(e);
        }

        private void fillgrid()
        {
            StringBuilder sb = new StringBuilder();
            StringBuilder sb2 = new StringBuilder();
            StringBuilder errsb = new StringBuilder();
            StringBuilder errsb2 = new StringBuilder();

            List<Task> tasklist = new List<Task>();
            TaskFactory taskfactory = new TaskFactory();
            tasklist.Add(taskfactory.StartNew(() =>
            {
                //有发料或调拔料的用料清单就不再考虑
                string billtype = ((DynamicObject)this.Model.GetValue("FBillTypeID"))["Name"].ToString();
                if (billtype == "按物料修改")
                {
                    sb.AppendLine("/*dialect*/ select b.FSEQ,a.FBILLNO,a.FMOTYPE,a.FWORKSHOPID,a.FMOBILLNO,b.FBOMID,b.FNEEDQTY,b.FENTRYID,b.fmustqty,b.fmustqty-c.FSELPICKEDQTY-c.FSELTRANSLATEQTY+c.FSELPRCDRETURNQTY as followqty,a.FCREATEDATE,a.FMATERIALID as parentpartno");
                    sb.AppendLine("  from T_PRD_PPBOMENTRY b with(nolock) inner join T_PRD_PPBOM a  with(nolock) on a.fid=b.FID  inner join T_PRD_PPBOMENTRY_Q c  with(nolock) on  c.FENTRYID=b.FENTRYID");
                    sb.AppendLine(" inner join T_PRD_MO d  with(nolock) on a.FMOBILLNO=d.FBILLNO  inner join T_PRD_MOENTRY_A f  with(nolock) on f.FENTRYID=a.FMOENTRYID");
                    sb.AppendLine(string.Format("where b.FMATERIALID={0} and b.FMUSTQTY>0 and a.FPRDORGID={1} and f.FSTATUS<>6 and not exists(select 1 from T_PRD_PPBOMENTRY h where h.FID=a.FID and h.FMATERIALID={2})", spartno, orgid, tpartno));
                    sb.AppendLine(" and b.fmustqty-c.FSELPICKEDQTY-c.FSELTRANSLATEQTY+c.FSELPRCDRETURNQTY>0   order by b.FNEEDDATE");
                }
                else  //按用量修改
                {
                    string rate = Convert.ToString(Convert.ToDouble(this.Model.GetValue("FRate")) / 100);
                    if (tpartno != "") //按用量修改需求取物料的用量精度
                    {
                        using (IDataReader rd = DBServiceHelper.ExecuteReader(this.Context, string.Format("select a.FPrecision from T_BD_UNIT a inner join T_BD_MATERIALBASE b on a.FUNITID=b.FBASEUNITID  where b.FMATERIALID={0} ", tpartno)))
                        {
                            while (rd.Read())
                            { tjd = rd["FPrecision"].ToString(); }
                        }
                    }
                    if (tjd != "0")
                    {
                        //sb.AppendLine(string.Format("/*dialect*/ select b.FSEQ,a.FBILLNO,a.FMOTYPE,a.FWORKSHOPID,a.FMOBILLNO,b.FBOMID,b.FNEEDQTY,b.FENTRYID,b.fmustqty, convert(numeric,b.fmustqty*{0},{1})-c.FSELPICKEDQTY-c.FSELTRANSLATEQTY+c.FSCRAPQTY+c.FGOODRETURNQTY+c.FPRCDEFECTRETURNQTY as followqty,a.FCREATEDATE,a.FMATERIALID as parentpartno", rate, tjd));
                        sb.AppendLine(string.Format("/*dialect*/ select b.FSEQ,a.FBILLNO,a.FMOTYPE,a.FWORKSHOPID,a.FMOBILLNO,b.FBOMID,b.FNEEDQTY,b.FENTRYID,b.fmustqty, convert(numeric,b.fmustqty*{0},{1})-c.FSELPICKEDQTY-c.FSELTRANSLATEQTY+c.FSELPRCDRETURNQTY as followqty,a.FCREATEDATE,a.FMATERIALID as parentpartno", rate, tjd));
                        sb.AppendLine("  from T_PRD_PPBOMENTRY b with(nolock) inner join T_PRD_PPBOM a  with(nolock) on a.fid=b.FID  inner join T_PRD_PPBOMENTRY_Q c  with(nolock) on  c.FENTRYID=b.FENTRYID");
                        sb.AppendLine(" inner join T_PRD_MO d  with(nolock) on a.FMOBILLNO=d.FBILLNO  inner join T_PRD_MOENTRY_A f  with(nolock) on f.FENTRYID=a.FMOENTRYID");
                        sb.AppendLine(string.Format("where b.FMATERIALID={0} and b.FMUSTQTY>0 and a.FPRDORGID={1} and c.FSELPICKEDQTY=0 and c.FSELTRANSLATEQTY=0 and f.FSTATUS<>6 and not exists(select 1 from T_PRD_PPBOMENTRY h where h.FID=a.FID and h.FMATERIALID={2})", spartno, orgid, tpartno));
                        sb.AppendLine(string.Format(" and b.fmustqty*{0},{1})-c.FSELPICKEDQTY-c.FSELTRANSLATEQTY+c.FSELPRCDRETURNQTY>0  order by b.FNEEDDATE", rate, tjd));
                    }
                    else
                    {
                        //sb.AppendLine(string.Format("/*dialect*/ select b.FSEQ,a.FBILLNO,a.FMOTYPE,a.FWORKSHOPID,a.FMOBILLNO,b.FBOMID,b.FNEEDQTY,b.FENTRYID,b.fmustqty, CEILING(b.fmustqty*{0})-c.FSELPICKEDQTY-c.FSELTRANSLATEQTY+c.FSCRAPQTY+c.FGOODRETURNQTY+c.FPRCDEFECTRETURNQTY  as followqty,a.FCREATEDATE,a.FMATERIALID as parentpartno", rate));
                        sb.AppendLine(string.Format("/*dialect*/ select b.FSEQ,a.FBILLNO,a.FMOTYPE,a.FWORKSHOPID,a.FMOBILLNO,b.FBOMID,b.FNEEDQTY,b.FENTRYID,b.fmustqty, CEILING(b.fmustqty*{0})-c.FSELPICKEDQTY-c.FSELTRANSLATEQTY+c.FSELPRCDRETURNQTY  as followqty,a.FCREATEDATE,a.FMATERIALID as parentpartno", rate));
                        sb.AppendLine("  from T_PRD_PPBOMENTRY b with(nolock) inner join T_PRD_PPBOM a  with(nolock) on a.fid=b.FID  inner join T_PRD_PPBOMENTRY_Q c  with(nolock) on  c.FENTRYID=b.FENTRYID");
                        sb.AppendLine(" inner join T_PRD_MO d  with(nolock) on a.FMOBILLNO=d.FBILLNO  inner join T_PRD_MOENTRY_A f  with(nolock) on f.FENTRYID=a.FMOENTRYID");
                        sb.AppendLine(string.Format("where b.FMATERIALID={0} and b.FMUSTQTY>0 and a.FPRDORGID={1} and c.FSELPICKEDQTY=0 and c.FSELTRANSLATEQTY=0 and f.FSTATUS<>6 and not exists(select 1 from T_PRD_PPBOMENTRY h where h.FID=a.FID and h.FMATERIALID={2}) ", spartno, orgid, tpartno));
                        sb.AppendLine(string.Format(" and  CEILING(b.fmustqty*{0})-c.FSELPICKEDQTY-c.FSELTRANSLATEQTY+c.FSELPRCDRETURNQTY>0  order by b.FNEEDDATE", rate));
                    }
                }

                this.Model.DeleteEntryData("FEntity");
                Entity entity = (Entity)this.View.Model.BusinessInfo.GetEntryEntity("FEntity");
                DynamicObjectCollection dyEntity = this.View.Model.GetEntityDataObject(entity);
                this.Model.BeginIniti();

                using (IDataReader rd = DBServiceHelper.ExecuteReader(this.Context, sb.ToString()))
                {
                    int i = 1;
                    while (rd.Read())
                    {

                        DynamicObject newRow = new DynamicObject(dyEntity.DynamicCollectionItemPropertyType);
                        newRow = new DynamicObject(dyEntity.DynamicCollectionItemPropertyType);
                        newRow["Seq"] = i;
                        newRow["FYldh"] = rd["FBILLNO"];
                        newRow["FYldseq"] = rd["FSEQ"];
                        newRow["FMOType_Id"] = rd["FMOTYPE"];
                        newRow["FWorkshopID_Id"] = rd["FWORKSHOPID"];
                        newRow["FMono"] = rd["FMOBILLNO"];
                        newRow["FYldDate"] = rd["FCREATEDATE"];
                        newRow["FBomId_Id"] = rd["FBOMID"];
                        newRow["FParentMaterialId_Id"] = rd["parentpartno"];
                        newRow["FMustQty"] = rd["FNEEDQTY"];
                        newRow["FFllowQty"] = rd["fmustqty"];
                        newRow["FOldToSelectQty"] = rd["followqty"];
                        if (billtype == "按物料修改")
                        { newRow["FTMustQty"] = rd["followqty"]; }
                        else
                        { newRow["FOldQty"] = rd["followqty"]; }
                        newRow["FFPPBOMENTRYID"] = rd["FENTRYID"]; //用料单内码

                        i += 1;
                        dyEntity.Add(newRow);
                    }
                    if (i == 1)
                    { errsb.AppendLine("没有找到符合要求的用料清单！"); }
                }
                DBServiceHelper.LoadReferenceObject(this.Context, dyEntity.ToArray(), dyEntity.DynamicCollectionItemPropertyType, false);
                this.Model.EndIniti();
                this.View.UpdateView("FEntity");
            }));

            tasklist.Add(taskfactory.StartNew(() =>
            {
                //提示未显示的数据

                sb2.AppendLine("/*dialect*/ select b.FSEQ,a.FBILLNO,a.FMOTYPE,a.FWORKSHOPID,a.FMOBILLNO,b.FBOMID,b.FNEEDQTY,b.FENTRYID,b.fmustqty as followqty,a.FCREATEDATE,a.FMATERIALID as parentpartno");
                sb2.AppendLine("  from T_PRD_PPBOMENTRY b with(nolock) inner join T_PRD_PPBOM a  with(nolock) on a.fid=b.FID  inner join T_PRD_PPBOMENTRY_Q c  with(nolock) on  c.FENTRYID=b.FENTRYID");
                sb2.AppendLine(" inner join T_PRD_MO d  with(nolock) on a.FMOBILLNO=d.FBILLNO  inner join T_PRD_MOENTRY_A f  with(nolock) on f.FENTRYID=a.FMOENTRYID");
                sb2.AppendLine(string.Format("where b.FMATERIALID={0} and b.FMUSTQTY>0 and a.FPRDORGID={1} and (c.FSELPICKEDQTY<>0 or c.FSELTRANSLATEQTY<>0) and f.FSTATUS<>6 and not exists(select 1 from T_PRD_PPBOMENTRY h where h.FID=a.FID and h.FMATERIALID={2}) order by b.FNEEDDATE", spartno, orgid, tpartno));
                this.Model.DeleteEntryData("F_PAEZ_Entity");
                Entity entity2 = (Entity)this.View.Model.BusinessInfo.GetEntryEntity("F_PAEZ_Entity");
                DynamicObjectCollection dyEntity2 = this.View.Model.GetEntityDataObject(entity2);
                this.Model.BeginIniti();
                using (IDataReader rd = DBServiceHelper.ExecuteReader(this.Context, sb2.ToString()))
                {
                    int i = 1;
                    while (rd.Read())
                    {
                        DynamicObject newRow = new DynamicObject(dyEntity2.DynamicCollectionItemPropertyType);
                        newRow = new DynamicObject(dyEntity2.DynamicCollectionItemPropertyType);
                        newRow["Seq"] = i;
                        newRow["FYLQDH_S"] = rd["FBILLNO"];
                        newRow["FMOType_S_Id"] = rd["FMOTYPE"];
                        newRow["FWorkshopID_S_Id"] = rd["FWORKSHOPID"];
                        newRow["FMono_S"] = rd["FMOBILLNO"];
                        newRow["FParentMaterialId_S_Id"] = rd["parentpartno"];
                        i += 1;
                        dyEntity2.Add(newRow);
                    }
                }
                DBServiceHelper.LoadReferenceObject(this.Context, dyEntity2.ToArray(), dyEntity2.DynamicCollectionItemPropertyType, false);
                this.Model.EndIniti();
                this.View.UpdateView("F_PAEZ_Entity");
            }));

            Task.WaitAll(tasklist.ToArray());

            if (errsb.ToString() != "")
            {
                this.View.ShowErrMessage(errsb.ToString());
            }
        }
    }
}
